/**
 * 
 */
package es.aradesh.ministryassist.gui.ministry;

import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import es.aradesh.ministryassist.R;
import es.aradesh.ministryassist.db.DbAdapter;
import es.aradesh.ministryassist.db.HomeColumns;
import es.aradesh.ministryassist.db.StreetColumns;
import es.aradesh.ministryassist.logic.ministry.Home;
import es.aradesh.ministryassist.logic.ministry.HomeBuilder;
import es.aradesh.ministryassist.logic.ministry.MinistryElement;
import es.aradesh.ministryassist.logic.ministry.Street;
import es.aradesh.ministryassist.logic.ministry.StreetBuilder;
import es.aradesh.ministryassist.logic.ministry.Territory;
import es.aradesh.ministryassist.logic.ministry.TerritoryBuilder;

/**
 * @author xmorales
 * 
 */
public class MinistryActivity extends ListActivity {

	private static final int VIEW_TERRITORY = 0;
	private static final int VIEW_STREET = 1;
	private static final int VIEW_HOME = 2;

	private String[] defaultMsg;
	private DbAdapter mDb;
	private Territory territoryParent; // The territory parent
	private Street streetParent; // The street parent
	private Home buildingParent; // The building parent
	private MinistryElement contextPointer;
	private boolean listVoid;
	private int viewLayout;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.ListActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list);
		mDb = new DbAdapter(this);
		mDb.open();
		defaultMsg = new String[] { this.getString(R.string.noElements) };
		fillTerritories();

		// Button OnClick() Definitions
		Button addButton = (Button) findViewById(R.id.addButton);
		Button backButton = (Button) findViewById(R.id.backButton);
		registerForContextMenu(getListView());
		addButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent i = new Intent(view.getContext(), AddEditActivity.class);
				switch (viewLayout) {
				case VIEW_TERRITORY:
					i.putExtra(MinistryElement.OPERATION,
							MinistryElement.ACTIVITY_EDIT_TERRITORY);
					startActivityForResult(i,
							MinistryElement.ACTIVITY_EDIT_TERRITORY);
					break;
				case VIEW_STREET:
					i.putExtra(MinistryElement.OPERATION,
							MinistryElement.ACTIVITY_EDIT_STREET);
					i.putExtra(StreetColumns.TERRITORY_ID, territoryParent
							.getId());
					startActivityForResult(i, MinistryElement.ACTIVITY_EDIT_STREET);
					break;
				case VIEW_HOME:
					i.putExtra(MinistryElement.OPERATION,
							MinistryElement.ACTIVITY_EDIT_HOME);
					i.putExtra(HomeColumns.STREET_ID, streetParent.getId());
					if (buildingParent != null)
						i.putExtra(HomeColumns.BUILDING_ID, buildingParent
								.getId());
					startActivityForResult(i, MinistryElement.ACTIVITY_EDIT_HOME);
					break;
				}
			}
		});
		backButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				switch (viewLayout) {
				case VIEW_TERRITORY:
					Intent mIntent = new Intent();
					setResult(RESULT_OK, mIntent);
					finish();
					break;
				case VIEW_STREET:
					territoryParent = null;
					fillTerritories();
					break;
				case VIEW_HOME:
					if (buildingParent == null) {
						streetParent = null;
						fillStreets();
					} else {
						buildingParent = null;
						fillHomes();
					}
					break;
				}
			}
		});
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 *      android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case MinistryElement.ACTIVITY_EDIT_TERRITORY:
			fillTerritories();
			break;
		case MinistryElement.ACTIVITY_EDIT_STREET:
			fillStreets();
			break;
		case MinistryElement.ACTIVITY_EDIT_HOME:
		case MinistryElement.ACTIVITY_SHOW_HOME:
			fillHomes();
			break;
		}

	}

	private void fillTerritories() {
		viewLayout = VIEW_TERRITORY;
		List<Territory> terris = TerritoryBuilder.getTerritoryList(this.mDb);

		if (terris.isEmpty()) {
			// Show a default message
			listVoid = true;
			setListAdapter(new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, defaultMsg));
		} else {
			listVoid = false;
			setListAdapter(new ArrayAdapter<Territory>(this,
					android.R.layout.simple_list_item_1, terris));
		}
		// Change title and button description
		Button addTerritoryButton = (Button) findViewById(R.id.addButton);
		addTerritoryButton.setText(R.string.addterritory);
		//TextView title = (TextView) findViewById(R.id.TextTerritoryTitle);
		//title.setText(R.string.territoryTitle);
		this.setTitle(R.string.territoryTitle);
	}

	private void fillStreets() {
		viewLayout = VIEW_STREET;
		List<Street> streets = StreetBuilder.getStreetsByTerritory(mDb,
				territoryParent);
		if (streets.isEmpty()) {
			// Show a default message
			listVoid = true;
			setListAdapter(new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, defaultMsg));
		} else {
			listVoid = false;
			setListAdapter(new ArrayAdapter<Street>(this,
					android.R.layout.simple_list_item_1, streets));
		}
		// Change title and button description
		Button addStreetButton = (Button) findViewById(R.id.addButton);
		addStreetButton.setText(R.string.addstreet);
		//TextView title = (TextView) findViewById(R.id.TextTerritoryTitle);
		//title.setText(getString(R.string.StreetsFor) + " " + territoryParent);
		this.setTitle(getString(R.string.StreetsFor) + " " + territoryParent);
	}

	private void fillHomes() {
		viewLayout = VIEW_HOME;
		Home[] homes = new Home[1];
		String extra = "";
		if (buildingParent == null) {
			homes = HomeBuilder.getHomesByStreet(mDb, streetParent).toArray(
					homes);
		} else {
			homes = buildingParent.getFlats();
			extra = getString(R.string.HomesFor) + " ";
		}
		if (homes[0] == null) {
			// Show a default message
			listVoid = true;
			setListAdapter(new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, defaultMsg));
		} else {
			listVoid = false;
			setListAdapter(new ArrayAdapter<Home>(this,
					android.R.layout.simple_list_item_1, homes));
		}
		// Change title and button description
		Button addHomeButton = (Button) findViewById(R.id.addButton);
		addHomeButton.setText(R.string.addhome);
		//TextView title = (TextView) findViewById(R.id.TextTerritoryTitle);
		//title.setText(getString(R.string.HomesFor) + " " + extra + " " + streetParent.toString());
		this.setTitle(getString(R.string.HomesFor) + " " + extra 
				+ streetParent.toString());
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		// Object o = l.getItemAtPosition(position);
		Intent i = null;
		if (!l.getItemAtPosition(position).equals(defaultMsg[0])) {
			switch (viewLayout) {
			case VIEW_TERRITORY:
				territoryParent = (Territory) l.getItemAtPosition(position);
				fillStreets();
				break;
			case VIEW_STREET:
				streetParent = (Street) l.getItemAtPosition(position);
				fillHomes();
				break;
			case VIEW_HOME:
				if (((Home) l.getItemAtPosition(position)).isBuilding()) {
					buildingParent = (Home) l.getItemAtPosition(position);
					fillHomes();
				} else {
					i = new Intent(v.getContext(), HomeDetailsActivity.class);
					i.putExtra(BaseColumns._ID, ((Home) l
							.getItemAtPosition(position)).getId());
					startActivityForResult(i, MinistryElement.ACTIVITY_SHOW_HOME);
				}
				break;
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		Intent i = new Intent(this, AddEditActivity.class);
		switch (item.getItemId()) {
		case MinistryElement.MENU_EDIT:
			i.putExtra(MinistryElement.OPERATION,
					contextPointer.getActivityEditType());
			i.putExtra(BaseColumns._ID, contextPointer.getId());
			startActivityForResult(i, contextPointer.getActivityEditType());
			break;
		case MinistryElement.MENU_DELETE:
			contextPointer.delete(mDb);
			onActivityResult(contextPointer.getActivityEditType(), RESULT_OK, i);
			break;
		}
		return super.onContextItemSelected(item);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu,
	 *      android.view.View, android.view.ContextMenu.ContextMenuInfo)
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (!listVoid) {
			AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
			menu.add(0, MinistryElement.MENU_EDIT, 0, R.string.edit);
			menu.add(0, MinistryElement.MENU_DELETE, 1, R.string.delete);
			contextPointer = (MinistryElement) ((ListView) v)
					.getItemAtPosition(new Long(info.id).intValue());
			super.onCreateContextMenu(menu, v, menuInfo);
		}
	}

}
